﻿using System;

using Microsoft.Xna.Framework;

using JigLibX.Physics;
using JigLibX.Collision;
using JigLibX.Math;




namespace FXnaEngine.Physics
{
    public class CharacterBody : QSBody
    {
        public CharacterBody(JigLibXActor actor)
            : base(actor)
        {
        }

        public Vector3 DesiredVelocity { get; set; }

        private bool doJump = false;

        public void DoJump()
        {
            doJump = true;
        }

        public override void AddExternalForces(float dt)
        {
            ClearForces();

            if (doJump)
            {
                foreach (CollisionInfo info in CollisionSkin.Collisions)
                {
                    Vector3 N = info.DirToBody0;
                    if (this == info.SkinInfo.Skin1.Owner)
                        Vector3.Negate(ref N, out N);

                    if (Vector3.Dot(N, Orientation.Up) > 0.7f)
                    {
                        Vector3 vel = Velocity;
                        vel.Y = 50.0f;
                        Velocity = vel;
                        break;
                    }
                }

                doJump = false;
            }

            // Very important, keeps player from rolling.
            this.AngularVelocity = Vector3.Zero;

            this.Velocity += DesiredVelocity + (this.additionalForce * dt);
            this.DesiredVelocity = Vector3.Zero;

            Vector3 velocityNoY = new Vector3(this.Velocity.X, 0.0f, this.Velocity.Z);

            float forceFactor = 2000.0f;
            AddWorldForce((-velocityNoY * (1 - (5 * dt))) * Mass * dt * forceFactor);

            AddGravityToExternalForce();
        }
    }
}
